<template>
  <div class="home">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>问卷总数</span>
            </div>
          </template>
          <div class="card-content">
            <el-statistic :value="dashboardData.totalSurveys">
              <template #prefix>
                <el-icon><Document /></el-icon>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>今日填写</span>
            </div>
          </template>
          <div class="card-content">
            <el-statistic :value="dashboardData.todayResponses">
              <template #prefix>
                <el-icon><Edit /></el-icon>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>活跃问卷数</span>
            </div>
          </template>
          <div class="card-content">
            <el-statistic :value="dashboardData.activeSurveys">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="mt-20">
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>问卷状态分布</span>
            </div>
          </template>
          <div class="chart-container">
            <el-empty v-if="!dashboardData.statusDistribution.length" description="暂无数据" />
            <div v-else id="status-chart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>最近7天问卷填写趋势</span>
            </div>
          </template>
          <div class="chart-container">
            <el-empty v-if="!dashboardData.weeklyTrend.length" description="暂无数据" />
            <div v-else id="trend-chart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="mt-20">
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>最近创建的问卷</span>
            </div>
          </template>
          <el-table :data="dashboardData.recentSurveys" style="width: 100%" v-loading="loading">
            <el-table-column prop="title" label="问卷标题" />
            <el-table-column prop="created_at" label="创建时间" />
            <el-table-column prop="status" label="状态">
              <template #default="{row}">
                <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{row}">
                <el-button type="primary" link @click="$router.push(`/edit/${row.id}`)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>最近填写的问卷</span>
            </div>
          </template>
          <el-table :data="dashboardData.recentResponses" style="width: 100%" v-loading="loading">
            <el-table-column prop="title" label="问卷标题" />
            <el-table-column prop="submit_time" label="提交时间" />
            <el-table-column prop="respondent" label="填写人" />
            <el-table-column label="操作" width="120">
              <template #default="{row}">
                <el-button type="primary" link @click="$router.push(`/results/${row.survey_id}`)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { Document, Edit, User } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

const router = useRouter()
const loading = ref(false)

const dashboardData = reactive({
  totalSurveys: 0,
  activeSurveys: 0,
  todayResponses: 0,
  recentSurveys: [],
  recentResponses: [],
  statusDistribution: [],
  weeklyTrend: []
})

const getStatusType = (status) => {
  const statusMap = {
    'active': 'success',
    'draft': 'info',
    'ended': 'warning'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'active': '进行中',
    'draft': '草稿',
    'ended': '已结束'
  }
  return statusMap[status] || status
}

const fetchDashboardData = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:3000/api/surveys/dashboard')
    if (response.data.code === 200) {
      const data = response.data.data
      Object.assign(dashboardData, data)
      
      // 渲染图表
      setTimeout(() => {
        if (dashboardData.statusDistribution.length) {
          renderStatusChart()
        }
        if (dashboardData.weeklyTrend.length) {
          renderTrendChart()
        }
      }, 0)
    }
  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
    ElMessage.error('获取仪表盘数据失败')
  } finally {
    loading.value = false
  }
}

const renderStatusChart = () => {
  const chartDom = document.getElementById('status-chart')
  if (!chartDom) return
  
  const myChart = echarts.init(chartDom)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: dashboardData.statusDistribution.map(item => getStatusText(item.name))
    },
    series: [
      {
        name: '问卷状态',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: dashboardData.statusDistribution.map(item => ({
          value: item.value,
          name: getStatusText(item.name)
        }))
      }
    ]
  }
  myChart.setOption(option)
  
  window.addEventListener('resize', () => {
    myChart.resize()
  })
}

const renderTrendChart = () => {
  const chartDom = document.getElementById('trend-chart')
  if (!chartDom) return
  
  const myChart = echarts.init(chartDom)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dashboardData.weeklyTrend.map(item => item.date)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: dashboardData.weeklyTrend.map(item => item.count),
        type: 'line',
        smooth: true,
        areaStyle: {}
      }
    ]
  }
  myChart.setOption(option)
  
  window.addEventListener('resize', () => {
    myChart.resize()
  })
}

onMounted(() => {
  fetchDashboardData()
})
</script>

<style scoped>
.home {
  padding: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  text-align: center;
  padding: 20px 0;
}

.el-statistic {
  font-size: 24px;
}

.chart-container {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>